/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * QASystemFrame.java
 *
 * Created on Apr 24, 2012, 9:36:14 AM
 */
package QASystem;

import DCGTree.Node;
import GraphViz.GraphViz;
import GraphViz.ImagePanel;
import QuestionGenerator.QAGenerator;
import QuestionGenerator.TypeQuestion;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Raito
 */
public class QASystem extends javax.swing.JFrame {

    List<TypeQuestion> question = new ArrayList<TypeQuestion>();
    boolean isAnswered = false;

    /** Creates new form QASystemFrame */
    public QASystem() {
        initComponents();
        InitData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        btnParse = new javax.swing.JButton();
        tfQuestion = new javax.swing.JTextField();
        btnGenerate = new javax.swing.JButton();
        cbTypeQuestion = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        tfSentence = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listAnswer = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        lbNumber = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        lbSyntax = new javax.swing.JLabel();
        lbType = new javax.swing.JLabel();
        lbSemantic = new javax.swing.JLabel();
        jPanel1 = new ImagePanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("QA System");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setIconImages(null);

        btnParse.setText("Trả lời");
        btnParse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnParseActionPerformed(evt);
            }
        });

        btnGenerate.setText("Sinh câu hỏi");
        btnGenerate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerateActionPerformed(evt);
            }
        });

        cbTypeQuestion.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTypeQuestionItemStateChanged(evt);
            }
        });

        tfSentence.setText("Mẫu :");

        listAnswer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listAnswerMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listAnswer);

        jLabel1.setText("Dạng câu hỏi : ");

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 459, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 166, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbSyntax, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
                    .addComponent(lbSemantic, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbType)
                .addGap(16, 16, 16)
                .addComponent(lbSyntax)
                .addGap(18, 18, 18)
                .addComponent(lbSemantic)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jScrollPane3.setViewportView(jPanel2);

        jMenu1.setText("Hệ Thống Hỏi Đáp");
        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btnGenerate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbTypeQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbNumber))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(tfQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnParse))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tfSentence)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 736, Short.MAX_VALUE)
                        .addComponent(jLabel4))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 408, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnGenerate)
                            .addComponent(jLabel1)
                            .addComponent(cbTypeQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbNumber))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfSentence, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jLabel4)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnParse))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnParseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnParseActionPerformed
// TODO add your handling code here:
//    this.setSize(1200, 750);
    this.setExtendedState(this.getExtendedState()|JFrame.MAXIMIZED_BOTH);
    isAnswered = true;
    String text = tfQuestion.getText();
    try {
        if (!"".equals(text)) {
            String type = QAProvider.getSyntaxName(text);
            if (type != null) {
                lbType.setText("Dạng : " + type);
                String syntax = QAProvider.loadSyntaxFile(text);
                if (syntax != null) {
                    lbSyntax.setText("Cú pháp : " + syntax);
                    String semantic = QAProvider.loadSemanticFile(text);
                    if (semantic != null) {
                        lbSemantic.setText("Ngữ nghĩa : " + semantic);
                        List<String> result = QAProvider.loadBrainFile(semantic, type);
                        String allsolution = "";
                        for (String s : result) {
                            allsolution += s + "\n";
                        }
                        type = QAProvider.findTypeQuestion(type);
                        String patternAnswer = QAProvider.getPatternAnswer(syntax);
                        final List<String> allResults;
                        if (!type.equals("4")) {
                            allResults = QAProvider.generateAnswer(patternAnswer, result);
                        } else {
                            patternAnswer = QAProvider.getPatternAnswerTypeFour(syntax);
                            allResults = QAProvider.answer(semantic, result);
                        }
                        if (allResults.isEmpty()) {
                            JOptionPane.showMessageDialog(null, "Không có câu trả lời", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                        }
                        listAnswer.setModel(new javax.swing.AbstractListModel() {

                            String[] strings = allResults.toArray(new String[allResults.size()]);

                            public int getSize() {
                                return strings.length;
                            }

                            public Object getElementAt(int i) {
                                return strings[i];
                            }
                        });
                    }


                    GraphViz gv = QAProvider.generateDotLanguage(syntax);
                    ImagePanel graph = (ImagePanel) jPanel1;
                    graph.setImage(gv);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Không nhận được dạng câu hỏi", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Hãy nhập câu hỏi", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception ex) {
        Logger.getLogger(QASystem.class.getName()).log(Level.SEVERE, null, ex);
    }
}//GEN-LAST:event_btnParseActionPerformed

private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateActionPerformed
// TODO add your handling code here:
    isAnswered = false;
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            final String[] generatedQuestions = generateQuestions();
            listAnswer.setModel(new javax.swing.AbstractListModel() {

                String[] strings = generatedQuestions;

                public int getSize() {
                    return strings.length;
                }

                public Object getElementAt(int i) {
                    return strings[i];
                }
            });
            
            lbNumber.setText("Gồm có : "+generatedQuestions.length + " câu hỏi");

        }
    });
    t.start();

}//GEN-LAST:event_btnGenerateActionPerformed

    private String[] generateQuestions() {
        int index = cbTypeQuestion.getSelectedIndex();
        System.out.println(question.get(index).getPattern());
        QAGenerator generate = new QAGenerator();
        List<String> patterns = question.get(index).getPattern();
        List<String> initQuestion = generate.initQuestion(patterns);
        return initQuestion.toArray(new String[initQuestion.size()]);
    }

private void cbTypeQuestionItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTypeQuestionItemStateChanged
    // TODO add your handling code here:   
    int index = cbTypeQuestion.getSelectedIndex();
    tfSentence.setText("Mẫu : " + question.get(index).getSentence());
}//GEN-LAST:event_cbTypeQuestionItemStateChanged

private void listAnswerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listAnswerMouseClicked
// TODO add your handling code here:
    if (!isAnswered) {
        int index = listAnswer.locationToIndex(evt.getPoint());
        Object item = listAnswer.getModel().getElementAt(index);
        tfQuestion.setText(item.toString());
    }
}//GEN-LAST:event_listAnswerMouseClicked

    private void InitData() {
        QAGenerator generate = new QAGenerator();
        question = generate.initData();
        for (TypeQuestion type : question) {
            cbTypeQuestion.addItem(type.getType());

        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");

            // start application
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(QASystem.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(QASystem.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(QASystem.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(QASystem.class.getName()).log(Level.SEVERE, null, ex);
        }


        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new QASystem().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGenerate;
    private javax.swing.JButton btnParse;
    private javax.swing.JComboBox cbTypeQuestion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lbNumber;
    private javax.swing.JLabel lbSemantic;
    private javax.swing.JLabel lbSyntax;
    private javax.swing.JLabel lbType;
    private javax.swing.JList listAnswer;
    private javax.swing.JTextField tfQuestion;
    private javax.swing.JLabel tfSentence;
    // End of variables declaration//GEN-END:variables
}
